// 国际化在设计时无法看，需要兼容下
const Funcs = window.Funcs || {
  GetTerms: (c, n) => n,
};

function fieldToTagCode({ tagFilterCode }) {
  return `${tagFilterCode}`;
}

function fieldToFilterExpression({
  tableCode,
  fieldCode,
  tagFilterValue,
  fieldName,
  tagFilterCondition = 'in',
}) {
  return {
    ElementType: 'Filter',
    Code: `${tableCode}.${fieldCode}`,
    Condition: tagFilterCondition,
    ValueType: 0,
    Name: fieldName,
    Value: tagFilterValue,
  };
}

export function fieldsToShowList(fields = []) {
  return fields.map(item => ({
    code: fieldToTagCode(item),
    name: Funcs.GetTerms(
      item?.ValueInfo_tagFilterShowName?.expr,
      item.tagFilterShowName,
    ),
    tip: Funcs.GetTerms(
      item?.ValueInfo_tagFilterShowTip?.expr,
      item.tagFilterShowTip,
    ),
  }));
}

// 根据选中条件获取Filters条件
export function getFilterExpressionBySelected(fields = [], selectedCodeList) {
  const list = fields
    .filter(v => selectedCodeList.has(fieldToTagCode(v)))
    .map(v => fieldToFilterExpression(v));
  let Filters = [];
  const listLen = list.length;
  if (listLen > 1) {
    list.forEach((item, index) => {
      if (index !== 0) {
        Filters.push({
          ElementType: 'Relation',
          Relation: 'and',
        });
      }
      Filters.push(item);
    });
  } else if (listLen == 1) {
    Filters = list;
  }

  return Filters.length > 0
    ? {
        ElementType: 'Group',
        Filters,
      }
    : {};
}

// 和外部查询条件合并
export function getMergeFilterExpression(tagFilter, advancedFilter) {
  let { Filters } = tagFilter;

  if (advancedFilter) {
    if (typeof advancedFilter === 'string') {
      try {
        advancedFilter = JSON.parse(advancedFilter);
      } catch (error) {
        console.warn('TagFilter.getMergeFilterExpression', error);
      }
    }
    if (false === tagFilter.hasOwnProperty('ElementType')) {
      /** 当 传入了 过滤条件 但是快速过滤本身没有条件时，直接返回传入的条件 */
      return advancedFilter;
    }

    if (advancedFilter.Filters && advancedFilter.Filters.length > 0) {
      if (Filters) {
        Filters?.push({
          ElementType: 'Relation',
          Relation: 'and',
        });
        Filters?.push(advancedFilter);
      } else {
        Filters = advancedFilter.Filters;
      }
    }
  }

  const returnValue = { ...tagFilter, Filters };
  return returnValue.hasOwnProperty('ElementType') ? returnValue : null;
}
